<template>
  <div>
    <!-- 面包屑区域 开始 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑区域 结束 -->
    <!-- 卡片区域 开始 -->
    <el-card>
      <!-- 警告提示区域 开始 -->
      <div>
        <el-alert
          type="warning"
          description="注意：只允许为第三级分类设置相关参数！"
          show-icon
          :closable="false"
        >
        </el-alert>
      </div>
      <!-- 警告提示区域 结束 -->
      <!-- 商品分类选择级联选择器区域 开始 -->
      <!-- v-model绑定的是你选择的值，是一个数组， optios是你绑定的要渲染的数据  props配置渲染options绑定的数据中的哪些数据，label属性展示的内容，value是选中的值 -->
      <div>
        <span>选择商品分类：</span>
        <el-cascader
          v-model="cascaderValueArr"
          :options="goodsCateList"
          :props="{
            expandTrigger: 'hover',
            label: 'cat_name',
            value: 'cat_id',
          }"
          @change="cascaderHandleChange"
        ></el-cascader>
      </div>
      <!-- 商品分类选择级联选择器区域 结束 -->
      <!-- 动态参数 静态属性区域 开始 -->
      <el-tabs v-model="tabActiveName" @tab-click="tabHandleClick">
        <!-- 动态参数区域 开始 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="cascaderValueArr.length === 3 ? false : true"
            @click="addParamsDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 表格展示区域 开始-->
          <el-table :data="paramsManyCate" style="width: 100%" border>
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="tagCloseDelete(row, i)"
                  >{{ item }}</el-tag
                >
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="分类名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  icon="el-icon-edit"
                  type="primary"
                  size="mini"
                  @click="editParamsDialog(row)"
                  >编辑</el-button
                >
                <el-button
                  icon="el-icon-edit"
                  type="danger"
                  size="mini"
                  @click="deleteParams(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 表格展示区域 结束 -->
        </el-tab-pane>
        <!-- 动态参数区域 结束 -->
        <!-- ----------------------- -->
        <!-- ----------------------- -->
        <!-- 静态属性区域 开始 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="cascaderValueArr.length === 3 ? false : true"
            @click="addParamsDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 表格展示区域 开始-->
          <el-table :data="paramsOnlyCate" style="width: 100%" border>
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="tagCloseDelete(row, i)"
                  >{{ item }}</el-tag
                >
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="分类名称">
            </el-table-column>
            <el-table-column label="操作">
              <template>
                <el-button icon="el-icon-edit" type="primary" size="mini"
                  >编辑</el-button
                >
                <el-button icon="el-icon-edit" type="danger" size="mini"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 表格展示区域 结束 -->
        </el-tab-pane>
        <!-- 静态属性区域 结束 -->
      </el-tabs>
      <!-- 动态参数 静态属性区域 结束 -->
    </el-card>
    <!-- 卡片区域 结束 -->
    <!-- 添加参数和添加属性共用一个对话框 开始 -->
    <el-dialog
      :title="'添加' + addParamsText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="$refs.addParamsform.resetFields()"
    >
      <el-form
        ref="addParamsform"
        :model="addParamsform"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item :label="addParamsText" prop="attr_name">
          <el-input v-model="addParamsform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参数和添加属性共用一个对话框 结束 -->

    <!-- 修改参数和添加属性共用一个对话框 开始 -->
    <el-dialog
      :title="'修改' + addParamsText"
      :visible.sync="eidtParamsDialogVisible"
      width="50%"
      @close="$refs.editParamsform.resetFields()"
    >
      <el-form
        ref="editParamsform"
        :model="editParamsform"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item :label="addParamsText" prop="attr_name">
          <el-input v-model="editParamsform.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidtParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="eidtParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数和添加属性共用一个对话框 结束 -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 对话框部分
      addParamsDialogVisible: false,
      eidtParamsDialogVisible: false,
      // 商品分类数据列表
      goodsCateList: [],
      // 级联选择器选中分类后值组成的数组
      cascaderValueArr: [],
      // 级联选择器是否重新出发
      cascaderIsChange: false,
      cascaderValueArrCache: [],
      // tab选中值
      tabActiveName: 'many',
      // table表格中的数据
      // 动态参数表格
      paramsManyCate: [],
      // 静态参数表格
      paramsOnlyCate: [],
      // 添加动态属性或者静态参数
      addParamsform: {
        attr_name: ''
      },
      // 编辑动态属性或者静态参数
      editParamsform: {
        attr_name: ''
      },
      // 验证规则
      rules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.getGoodsCateList()
  },

  methods: {
    // 获取商品分类列表
    async getGoodsCateList() {
      const res = await this.$axios.get('/categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.goodsCateList = res.data
    },
    // 级联选择器的值发生变化
    cascaderHandleChange() {
      // this.cascaderIsChange = true
      this.getParamscate()
    },
    // tab点击标签
    tabHandleClick() {
      if (this.cascaderValueArr.length === 0) {
        return
      }
      // if (this.cascaderIsChange) {
      //   this.getParamscate()
      //   this.cascaderValueArrCache = this.cascaderValueArr
      //   this.cascaderIsChange = false
      // }
      this.getParamscate()
    },
    // 获取指定分类参数数据
    async getParamscate() {
      const len = this.cascaderValueArr.length
      if (len !== 3) {
        this.$message.error('选择分类失败')
        this.cascaderValueArr = []
        this.paramsManyCate = []
        this.paramsOnlyCate = []
        return
      }
      // const id = this.cascaderValueArr[len - 1]
      const res = await this.$axios.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.tabActiveName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数失败')
      }
      // 把原始数据中的attr_vals的值分割称数组
      res.data.forEach(item => {
        // 先判断一下attr_vals是否为一个空字符串，如果是一个空字符串得到的数组是一个包含一项为空字符串的数组
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        // 给每一行添加独有的属性
        item.inputVisible = false
        item.inputValue = ''
      })
      this.tabActiveName === 'only'
        ? (this.paramsOnlyCate = res.data)
        : (this.paramsManyCate = res.data)
      this.$message.success('获取分类参数成功')
    },
    // 点击添加属性对话框确定按钮
    addParams() {
      this.$refs.addParamsform.validate(async flag => {
        if (!flag) return
        const res = await this.$axios.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsform.attr_name,
            attr_sel: this.tabActiveName
          }
        )
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.addParamsDialogVisible = false
        this.$message.success('添加成功')
        this.getParamscate()
      })
    },
    // 点击动态参数表格里的删除按钮
    deleteParams(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$axios.delete(
            `categories/${this.cateId}/attributes/${row.attr_id}`
          )
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.getParamscate()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击动态参数表格里的编辑按钮
    editParamsDialog(row) {
      // console.log(row)
      this.editParamsform.attr_name = row.attr_name
      this.editParamsform.attr_id = row.attr_id
      this.eidtParamsDialogVisible = true
    },
    // 点击动态参数表格里的编辑对话框的确定按钮
    eidtParams() {
      this.$refs.editParamsform.validate(async flag => {
        if (!flag) return
        const res = await this.$axios.put(
          `categories/${this.cateId}/attributes/${this.editParamsform.attr_id}`,
          {
            attr_name: this.editParamsform.attr_name,
            attr_sel: this.tabActiveName
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.eidtParamsDialogVisible = false
        this.getParamscate()
        this.$message.success('修改成功')
      })
    },
    async handleInputConfirm(row) {
      // 输入框为空不发送请求
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        return
      }
      // 把输入框的值push进数组
      row.attr_vals.push(row.inputValue)
      const res = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.tabActiveName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      // const res = await this.fn(row)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('添加失败')
      }
      row.inputValue = ''
      row.inputVisible = false
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async tagCloseDelete(row, index) {
      row.attr_vals.splice(index, 1)
      const res = await this.$axios.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.tabActiveName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
    },
    async fn(row, index) {
      if (index !== undefined) {
        row.attr_vals.splice(index, 1)
      } else {
        row.attr_vals.push(row.inputValue)
        console.log('添加')
      }
      const res = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.tabActiveName,
        attr_vals: row.attr_vals.join(' ')
      })
      return res
    }
  },
  computed: {
    // 计算属性是data中某个值的变化引起计算属性中某个属性的变化，并且计算属性可以缓存
    cateId() {
      if (this.cascaderValueArr.length !== 3) return null
      return this.cascaderValueArr[2]
    },
    // 动态显示添加属性或者参数对话框的标题文本部分
    addParamsText() {
      return this.tabActiveName === 'only' ? '静态属性' : '动态参数'
    }
  }
}
</script>

<style scoped lang='less'>
.el-cascader {
  margin: 10px 0;
}
.el-tag {
  margin: 8px;
}
.input-new-tag {
  width: 100px;
}
</style>
